package repeat2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-10-12
 * Time: 9:57
 */
public class TcpEchoServer {
    //socket文件来读写
    private ServerSocket serverSocket = null;//拉客
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动\n");
        while(true){
            //一次连接
            Socket socketClient = serverSocket.accept();//拉完客了给接待
            System.out.printf("[%s %d]客户端已上线\n",socketClient.getInetAddress(),socketClient.getPort());
            processConnection(socketClient);

        }

    }
    public void processConnection(Socket socketClient){
        //面向字节流
        try(InputStream inputStream = socketClient.getInputStream();
            OutputStream outputStream = socketClient.getOutputStream()){
            while(true){
                /*
                byte[] buffer = new byte[1024];
                inputStream.read(buffer);//数组再转字符串
                */
                //接收请求
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.printf("[%s %d]客户端断开连接\n", socketClient.getInetAddress(), socketClient.getPort());
                    break;
                }
                String request = scanner.next();
                String response = process(request);
                //怎么发送呢？write不建议,封装outStream
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                System.out.printf("[%s %d] , req: %s resp: %s\n",socketClient.getInetAddress(),socketClient.getPort(),request,response);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9091);
        server.start();
    }
}
